<template>
  <div class="simplemde-markdown-editor">
    <div class="bar-right" :class="{ fullscreen }">
      <slot name="bar-right"></slot>
    </div>
    <slot />
    <textarea ref="editor" />
  </div>
</template>

<script lang="ts">
import 'simplemde/dist/simplemde.min.css'
import { Component, Vue, Prop } from 'vue-property-decorator'
let Simplemde: any = null
if (typeof window !== 'undefined') {
  Simplemde = require('simplemde')
}

@Component({
  name: 'SimplemdeEditor'
})
export default class SimplemdeEditor extends Vue {
  // 初始数据
  @Prop({ type: String, default: '' }) value!: string
  @Prop({ type: Object, default: () => ({}) }) options!: object

  // 编辑器对象
  editor: any = null
  // 是否是全屏
  fullscreen = false
  timer: NodeJS.Timeout | null = null

  mounted () {
    this.editor = new Simplemde(
      Object.assign(this.options, {
        element: this.$refs.editor,
        showIcons: [
          'table',
          'horizontal-rule',
          'link',
          'code',
          'strikethrough',
          'heading',
          'heading-smaller',
          'heading-bigger'
        ],
        insertTexts: {
          image: ['<img src="" width = "400"/>']
        }
      })
    )
    if (this.value) {
      this.editor.value(this.value)
    }
    this.createTimer()
  }

  beforeDestroy () {
    this.clearTimer()
  }

  /**
   * 设置数据
   */
  setData (value: string) {
    this.editor.value(value)
  }

  /**
   * 获取数据
   * @returns {*}
   */
  getData () {
    return this.editor.value()
  }

  createTimer () {
    this.clearTimer()
    this.timer = setInterval(() => {
      this.fullscreen = this.editor.isFullscreenActive()
    }, 200)
  }

  clearTimer () {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
  }
}
</script>

<style lang="less">
.simplemde-markdown-editor {
  position: relative;
  .editor-toolbar.fullscreen {
    z-index: 9999;
  }
  .CodeMirror-fullscreen {
    z-index: 9999;
  }

  .CodeMirror-fullscreen ~ .editor-preview-side {
    z-index: 9999;
  }
  .bar-right {
    position: absolute;
    right: 0;
    top: 0;
    height: 48px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    z-index: 100;
  }
  .bar-right.fullscreen {
    position: fixed;
    z-index: 10000;
  }
}
</style>
